﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
using CommDll;
using DevComponents.DotNetBar;
using System.Drawing.Imaging;
using System.Globalization;
using System.DirectoryServices.ActiveDirectory;
using Padding = DevComponents.DotNetBar.Padding;

namespace HospitalMedicineTraceability
{
    public partial class frmCollectPharmacyStockOut_Bat : DevComponents.DotNetBar.OfficeForm
    {
        public Dictionary<string, string> m_dictInfo = new Dictionary<string, string>();
        public DataTable m_dt = new DataTable();
        public Boolean m_bIsRefresh = false;    //是否刷新数据
        public string m_strBillCode = "";
        public string m_strSupervisionCode = "";
        // 扫码商品信息
        private Dictionary<string, string> m_dictCode = new Dictionary<string, string>();
        private Dictionary<string, PanelEx> m_dictPnl = new Dictionary<string, PanelEx>();
        private Dictionary<string, LabelX> m_dictGoodsName = new Dictionary<string, LabelX>();
        private Dictionary<string, LabelX> m_dictGoodsSpec = new Dictionary<string, LabelX>();
        private Dictionary<string, LabelX> m_dictAmount = new Dictionary<string, LabelX>();
        private Dictionary<string, LabelX> m_dictCollectAmount = new Dictionary<string, LabelX>();
        private Dictionary<string, LabelX> m_dictCollectCount = new Dictionary<string, LabelX>();
        private Dictionary<string, LabelX> m_dictCollectStatus  = new Dictionary<string, LabelX>();
        private Dictionary<string, LabelX> m_dictSupervisionCodeStatus = new Dictionary<string, LabelX>();
        public frmCollectPharmacyStockOut_Bat()
        {
            InitializeComponent();
            timerShowData.Enabled = false;            
        }

        #region 01 自定义方法

        // 初始化批量控件
        private void _initCtrl(int nCount)
        {
            int nOrder = m_dictPnl.Count;
            if (nOrder >= nCount) {
                return;
            }
            for (int i = nOrder+1; i <= nCount; i++)
            {
                if (i != 1)
                {
                    DevComponents.DotNetBar.PanelEx pnlTemp = new DevComponents.DotNetBar.PanelEx();
                    pnlTemp.Name = "pnl" + i.ToString();
                    pnlTemp.Top = pnl1.Top + ((((i + 1) / 2 - 1)) * (pnl1.Height + 10));
                    pnlTemp.Left = pnl1.Left + (i % 2 == 0 ? pnl1.Width + 10 : 0);
                    pnlTemp.Width = pnl1.Width;
                    pnlTemp.Height = pnl1.Height;
                    pnlTemp.Style.Border = pnl1.Style.Border;
                    pnlTemp.Style.BorderColor.Color = pnl1.Style.BorderColor.Color;
                    pnlTemp.Style.BorderWidth = pnl1.Style.BorderWidth;
                    pnlTemp.Visible = pnl1.Visible;
                    pnlScan.Controls.Add(pnlTemp);

                    Label lblGoodsName = new Label();
                    lblGoodsName.Name = "lblGoodsName" + i.ToString();
                    lblGoodsName.Top = lblGoodsName1.Top;
                    lblGoodsName.Left = lblGoodsName1.Left;
                    lblGoodsName.Width = lblGoodsName1.Width;
                    lblGoodsName.Height = lblGoodsName1.Height;
                    lblGoodsName.Text = lblGoodsName1.Text;
                    lblGoodsName.Font = lblGoodsName1.Font;
                    pnlTemp.Controls.Add(lblGoodsName);

                    LabelX txtGoodsName = new LabelX();
                    txtGoodsName.Name = "txtGoodsName" + i.ToString();
                    txtGoodsName.Top = txtGoodsName1.Top;
                    txtGoodsName.Left = txtGoodsName1.Left;
                    txtGoodsName.Width = txtGoodsName1.Width;
                    txtGoodsName.Height = txtGoodsName1.Height;
                    txtGoodsName.Text = txtGoodsName1.Text;
                    txtGoodsName.Font = txtGoodsName1.Font;
                    txtGoodsName.BackgroundStyle.BorderBottom = txtGoodsName1.BackgroundStyle.BorderBottom;
                    txtGoodsName.BackgroundStyle.BorderBottomColor = txtGoodsName1.BackgroundStyle.BorderBottomColor;
                    txtGoodsName.BackgroundStyle.BorderBottomWidth = txtGoodsName1.BackgroundStyle.BorderBottomWidth;

                    pnlTemp.Controls.Add(txtGoodsName);

                    Label lblGoodsSpec = new Label();
                    lblGoodsSpec.Name = "lblGoodsSpec" + i.ToString();
                    lblGoodsSpec.Top = lblGoodsSpec1.Top;
                    lblGoodsSpec.Left = lblGoodsSpec1.Left;
                    lblGoodsSpec.Width = lblGoodsSpec1.Width;
                    lblGoodsSpec.Height = lblGoodsSpec1.Height;
                    lblGoodsSpec.Text = lblGoodsSpec1.Text;
                    lblGoodsSpec.Font = lblGoodsSpec1.Font;
                    pnlTemp.Controls.Add(lblGoodsSpec);

                    LabelX txtGoodsSpec = new LabelX();
                    txtGoodsSpec.Name = "txtGoodsSpec" + i.ToString();
                    txtGoodsSpec.Top = txtGoodsSpec1.Top;
                    txtGoodsSpec.Left = txtGoodsSpec1.Left;
                    txtGoodsSpec.Width = txtGoodsSpec1.Width;
                    txtGoodsSpec.Height = txtGoodsSpec1.Height;
                    txtGoodsSpec.Text = txtGoodsSpec1.Text;
                    txtGoodsSpec.Font = txtGoodsSpec1.Font;
                    txtGoodsSpec.BackgroundStyle.BorderBottom = txtGoodsSpec1.BackgroundStyle.BorderBottom;
                    txtGoodsSpec.BackgroundStyle.BorderBottomColor = txtGoodsSpec1.BackgroundStyle.BorderBottomColor;
                    txtGoodsSpec.BackgroundStyle.BorderBottomWidth = txtGoodsSpec1.BackgroundStyle.BorderBottomWidth;
                    pnlTemp.Controls.Add(txtGoodsSpec);

                    Label lblAmount = new Label();
                    lblAmount.Name = "lblAmount" + i.ToString();
                    lblAmount.Top = lblAmount1.Top;
                    lblAmount.Left = lblAmount1.Left;
                    lblAmount.Width = lblAmount1.Width;
                    lblAmount.Height = lblAmount1.Height;
                    lblAmount.Text = lblAmount1.Text;
                    lblAmount.Font = lblAmount1.Font;
                    pnlTemp.Controls.Add(lblAmount);

                    LabelX txtAmount = new LabelX();
                    txtAmount.Name = "txtAmount" + i.ToString();
                    txtAmount.Top = txtAmount1.Top;
                    txtAmount.Left = txtAmount1.Left;
                    txtAmount.Width = txtAmount1.Width;
                    txtAmount.Height = txtAmount1.Height;
                    txtAmount.Text = txtAmount1.Text;
                    txtAmount.AutoSize = txtAmount1.AutoSize;
                    txtAmount.BackColor = txtAmount1.BackColor;
                    txtAmount.Font = txtAmount1.Font;
                    txtAmount.ForeColor = txtAmount1.ForeColor;
                    txtAmount.TextAlignment = txtAmount1.TextAlignment;

                    pnlTemp.Controls.Add(txtAmount);

                    Label lblCollectAmount = new Label();
                    lblCollectAmount.Name = "lblCollectAmount" + i.ToString();
                    lblCollectAmount.Top = lblCollectAmount1.Top;
                    lblCollectAmount.Left = lblCollectAmount1.Left;
                    lblCollectAmount.Width = lblCollectAmount1.Width;
                    lblCollectAmount.Height = lblCollectAmount1.Height;
                    lblCollectAmount.Text = lblCollectAmount1.Text;
                    lblCollectAmount.Font = lblCollectAmount1.Font;
                    pnlTemp.Controls.Add(lblCollectAmount);

                    LabelX txtCollectAmount = new LabelX();
                    txtCollectAmount.Name = "txtCollectAmount" + i.ToString();
                    txtCollectAmount.Top = txtCollectAmount1.Top;
                    txtCollectAmount.Left = txtCollectAmount1.Left;
                    txtCollectAmount.Width = txtCollectAmount1.Width;
                    txtCollectAmount.Height = txtCollectAmount1.Height;
                    txtCollectAmount.Text = txtCollectAmount1.Text;
                    txtCollectAmount.AutoSize = txtCollectAmount1.AutoSize;
                    txtCollectAmount.BackColor = txtCollectAmount1.BackColor;
                    txtCollectAmount.Font = txtCollectAmount1.Font;
                    txtCollectAmount.ForeColor = txtCollectAmount1.ForeColor;
                    txtCollectAmount.TextAlignment = txtCollectAmount1.TextAlignment;

                    pnlTemp.Controls.Add(txtCollectAmount);

                    Label lblCollectStatus = new Label();
                    lblCollectStatus.Name = "lblCollectStatus" + i.ToString();
                    lblCollectStatus.Top = lblCollectStatus1.Top;
                    lblCollectStatus.Left = lblCollectStatus1.Left;
                    lblCollectStatus.Width = lblCollectStatus1.Width;
                    lblCollectStatus.Height = lblCollectStatus1.Height;
                    lblCollectStatus.Text = lblCollectStatus1.Text;
                    lblCollectStatus.Font = lblCollectStatus1.Font;
                    pnlTemp.Controls.Add(lblCollectStatus);

                    LabelX txtCollectStatus = new LabelX();
                    txtCollectStatus.Name = "txtCollectStatus" + i.ToString();
                    txtCollectStatus.Top = txtCollectStatus1.Top;
                    txtCollectStatus.Left = txtCollectStatus1.Left;
                    txtCollectStatus.Width = txtCollectStatus1.Width;
                    txtCollectStatus.Height = txtCollectStatus1.Height;
                    txtCollectStatus.Text = txtCollectStatus1.Text;
                    txtCollectStatus.AutoSize = txtCollectStatus1.AutoSize;
                    txtCollectStatus.BackColor = txtCollectStatus1.BackColor;
                    txtCollectStatus.Font = txtCollectStatus1.Font;
                    txtCollectStatus.ForeColor = txtCollectStatus1.ForeColor;
                    txtCollectStatus.TextAlignment = txtCollectStatus1.TextAlignment;
                    pnlTemp.Controls.Add(txtCollectStatus);

                    Label lblCollectCount = new Label();
                    lblCollectCount.Name = "lblCollectCount" + i.ToString();
                    lblCollectCount.Top = lblCollectCount1.Top;
                    lblCollectCount.Left = lblCollectCount1.Left;
                    lblCollectCount.Width = lblCollectCount1.Width;
                    lblCollectCount.Height = lblCollectCount1.Height;
                    lblCollectCount.Text = lblCollectCount1.Text;
                    lblCollectCount.Font = lblCollectCount1.Font;
                    pnlTemp.Controls.Add(lblCollectCount);

                    LabelX txtCollectCount = new LabelX();
                    txtCollectCount.Name = "txtCollectCount" + i.ToString();
                    txtCollectCount.Top = txtCollectCount1.Top;
                    txtCollectCount.Left = txtCollectCount1.Left;
                    txtCollectCount.Width = txtCollectCount1.Width;
                    txtCollectCount.Height = txtCollectCount1.Height;
                    txtCollectCount.Text = txtCollectCount1.Text;
                    txtCollectCount.AutoSize = txtCollectCount1.AutoSize;
                    txtCollectCount.BackColor = txtCollectCount1.BackColor;
                    txtCollectCount.Font = txtCollectCount1.Font;
                    txtCollectCount.ForeColor = txtCollectCount1.ForeColor;
                    txtCollectCount.TextAlignment = txtCollectCount1.TextAlignment;
                    // 显示电监码
                    txtCollectCount.DoubleClick += new System.EventHandler(this.txtCollectCount1_DoubleClick);
                    pnlTemp.Controls.Add(txtCollectCount);

                    LabelX txtSupervisionCodeStatus = new LabelX();
                    txtSupervisionCodeStatus.Name = "txtSupervisionCodeStatus" + i.ToString();
                    txtSupervisionCodeStatus.Top = txtSupervisionCodeStatus1.Top;
                    txtSupervisionCodeStatus.Left = txtSupervisionCodeStatus1.Left;
                    txtSupervisionCodeStatus.Width = txtSupervisionCodeStatus1.Width;
                    txtSupervisionCodeStatus.Height = txtSupervisionCodeStatus1.Height;
                    txtSupervisionCodeStatus.Text = txtSupervisionCodeStatus1.Text;

                    txtSupervisionCodeStatus.BackgroundStyle.CornerType = txtSupervisionCodeStatus1.BackgroundStyle.CornerType;
                    txtSupervisionCodeStatus.Font = txtSupervisionCodeStatus1.Font;
                    txtSupervisionCodeStatus.ForeColor = txtSupervisionCodeStatus1.ForeColor;                    
                    txtSupervisionCodeStatus.TextAlignment = txtSupervisionCodeStatus1.TextAlignment;
                    // 设置商品
                    txtSupervisionCodeStatus.DoubleClick += new System.EventHandler(this.lblSupervisionCodeStatus1_DoubleClick);
                    pnlTemp.Controls.Add(txtSupervisionCodeStatus);
                    // 赋值给数组
                    m_dictPnl.Add(i.ToString(),pnlTemp);
                    m_dictGoodsName.Add(i.ToString(), txtGoodsName);
                    m_dictGoodsSpec.Add(i.ToString(), txtGoodsSpec);
                    m_dictAmount.Add(i.ToString(), txtAmount);
                    m_dictCollectAmount.Add(i.ToString(), txtCollectAmount);
                    m_dictCollectStatus.Add(i.ToString(), txtCollectStatus);
                    m_dictCollectCount.Add(i.ToString(), txtCollectCount);
                    m_dictSupervisionCodeStatus.Add(i.ToString(), txtSupervisionCodeStatus);
                }
                else {
                    m_dictPnl.Add(i.ToString(), pnl1);
                    m_dictGoodsName.Add(i.ToString(), txtGoodsName1);
                    m_dictGoodsSpec.Add(i.ToString(), txtGoodsSpec1);
                    m_dictAmount.Add(i.ToString(), txtAmount1);
                    m_dictCollectAmount.Add(i.ToString(), txtCollectAmount1);
                    m_dictCollectStatus.Add(i.ToString(), txtCollectStatus1);
                    m_dictCollectCount.Add(i.ToString(), txtCollectCount1);
                    m_dictSupervisionCodeStatus.Add(i.ToString(), txtSupervisionCodeStatus1);
                }
            }
        }

        /// <summary>
        /// 显示单据信息
        /// </summary>
        /// <param name="strBillCode"></param>
        private Boolean _showBillInfo(string strBillCode)
        {
            Boolean bReturn = false;
            try
            {
                // 01 显示相关信息
                string strSql = string.Format("select PrescriptionCode,PatientIdCode,PatientName,Code,PickerName,SupervisionCodeCollectStatus from TH_PharmacyStockOut where Code = '{0}' or (PatientIdCode = '{0}' and isnull(SupervisionCodeCollectStatus,'') <> '全采') order by StockOutTime desc,Id desc", strBillCode);
                DataTable dt = AppInfo._openSql_DataTable(strSql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    if (dt.Rows[0]["SupervisionCodeCollectStatus"].ToString().Equals("全采"))
                    {
                        CommFun._messageBoxShow("该单据已采集完成，请换新单据！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return bReturn;
                    }
                    else
                    {
                        // 显示处方数据
                        m_strBillCode = dt.Rows[0]["Code"].ToString();
                        m_dictInfo["BillCode"] = m_strBillCode;
                        txtPrescriptionCode.Text = dt.Rows[0]["PrescriptionCode"].ToString();
                        txtPatientName.Text = dt.Rows[0]["PatientName"].ToString();
                        gbMain.Text = string.Format("单据信息(编号:{0})", m_strBillCode);

                        // 00 拆零等系统处理
                        strSql = string.Format("exec P_DealPharmacyStockOut 'Collect_SystemDeal','{0}@{1}@{2}'", m_strBillCode, AppInfo.m_UserInfo.m_strCode, AppInfo.m_UserInfo.m_strName);

                        dt = AppInfo._openSql_DataTable(strSql);
                        if (dt == null)
                        {
                            CommFun._messageBoxShow("系统拆零处理有误!");
                            return bReturn;
                        }
                        else
                        {
                            // 拆零有误
                            string strResultKind = dt.Rows[0]["Result"].ToString();
                            Boolean bResult = strResultKind.Equals("1");
                            if (!bResult)
                            {
                                CommFun._messageBoxShow(dt.Rows[0]["Message"].ToString());
                                return bReturn;
                            }
                            else {
                                bReturn = true;
                            }
                        }
                        // 隐藏单据页
                        pnlNext.Visible = false;
                    }
                }
                else
                {
                    CommFun._messageBoxShow("该单号不存在,请确认！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return bReturn;
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return bReturn;
        }

        /// <summary>
        /// 取单据明细信息(包含商品信息)
        /// </summary>
        private void _getBillList()
        {
            try
            {
                string strSql = @"select A.* from
(
select A.Id,StockOut_Code as BillCode
,DetailCode as BillDetailCode
,A.Code,A.Name,A.PackageSpec,A.Manufacturer
,Amount = Convert(varchar(10),Convert(float,Amount)) + A.Unit + case when case when isnull(PharmacyPackageRatio,0) = 0 then 1 else PharmacyPackageRatio end = 1 then '' else '/' + Convert(varchar(10),Convert(float,Convert(numeric(18,2),Amount / PharmacyPackageRatio))) + B.Unit end
,SupervisionCodeCollectAmount = Convert(float,SupervisionCodeCollectAmount)
,SupervisionCodeCollectCount
,SupervisionCodeCollectStatus = case when isnull(SupervisionCodeCollectStatus,'') = '' then '未采' else SupervisionCodeCollectStatus end
,SupervisionCodeStatus = case when B.IsSplitPackage = '是' then '拆零' when B.IsSupervisionCode = '否' then '无码' when isnull(B.IsSupervisionCode,'') = '' then '未设置' else '需采码' end
 from TH_PharmacyStockOutDetail A
 Left outer join TH_Goods B On A.Code = B.Code where A.StockOut_Code = '{0}'
)A
left outer join (
select Id,Value from dbo.F_Split('未采,部采,全采',',')
)B On A.SupervisionCodeCollectStatus = B.Value
order by B.Id,A.BillDetailCode";
                strSql = string.Format(strSql, m_strBillCode);
                m_dt = AppInfo._openSql_DataTable(strSql);
            }
            catch (Exception ex)
            {
                CommFun._messageBoxShow(ex.Message);
            }
            // 初始化商品信息(控件)
            if (m_dt != null && m_dt.Rows.Count > 0)
            {
                _initCtrl(m_dt.Rows.Count);
                gbScan.Text = string.Format("单据商品信息(记录数:{0})", m_dt == null ? 0 : m_dt.Rows.Count);
            }
            // 赋控件值(只显示有数据项)
            for (int i = 1; i <= m_dictPnl.Count; i++)
            {
                if (m_dt != null && m_dt.Rows.Count > 0 && i <= m_dt.Rows.Count)
                {
                    m_dictPnl[i.ToString()].Visible = true;
                    m_dictGoodsName[i.ToString()].Visible = true;
                    m_dictGoodsSpec[i.ToString()].Visible = true;
                    m_dictAmount[i.ToString()].Visible = true;
                    m_dictCollectAmount[i.ToString()].Visible = true;
                    m_dictCollectCount[i.ToString()].Visible = true;
                    m_dictCollectStatus[i.ToString()].Visible = true;
                    m_dictSupervisionCodeStatus[i.ToString()].Visible = true;

                    m_dictCode[i.ToString()] = m_dt.Rows[i - 1]["Code"].ToString();
                    m_dictGoodsName[i.ToString()].Text = m_dictGoodsName[i.ToString()].Text = string.Format("({0}){1}", m_dt.Rows[i - 1]["Code"].ToString(), m_dt.Rows[i - 1]["Name"].ToString());
                    m_dictGoodsSpec[i.ToString()].Text = m_dt.Rows[i - 1]["PackageSpec"].ToString();
                    m_dictAmount[i.ToString()].Text = m_dt.Rows[i - 1]["Amount"].ToString();
                    m_dictCollectAmount[i.ToString()].Text = m_dt.Rows[i - 1]["SupervisionCodeCollectAmount"].ToString();
                    m_dictCollectCount[i.ToString()].Text = m_dt.Rows[i - 1]["SupervisionCodeCollectCount"].ToString();
                    m_dictCollectCount[i.ToString()].BackColor = Color.Red;
                    m_dictCollectStatus[i.ToString()].Text = m_dt.Rows[i - 1]["SupervisionCodeCollectStatus"].ToString();
                    m_dictCollectStatus[i.ToString()].BackColor = m_dictCollectStatus[i.ToString()].Text.Equals("全采") ? Color.Red : Color.Black;
                    m_dictSupervisionCodeStatus[i.ToString()].Text = m_dt.Rows[i - 1]["SupervisionCodeStatus"].ToString();
                }
                else
                {
                    m_dictPnl[i.ToString()].Visible = false;
                }
            }            
            // 汇总数据
            _getBillTotal();
        }

        /// <summary>
        /// 取单据汇总数据
        /// </summary>
        private void _getBillTotal()
        {
            int nGoodsCount = 0; // 商品品种数
            int nGoodsCount1 = 0; // 已复核商品品种数
            int nGoodsCount0 = 0; // 未复核商品品种数
            double dGoodsCollectAmount = 0; // 已采数
            try
            {
                nGoodsCount = (m_dt == null)?0: m_dt.Rows.Count;                
                for (int i = 0; i < nGoodsCount; i++)
                {
                    if (m_dt.Rows[i]["SupervisionCodeCollectStatus"].ToString().Equals("全采"))
                    {
                        nGoodsCount1 += 1;
                    }
                    dGoodsCollectAmount += FunctionComm._strToFloat(m_dt.Rows[i]["SupervisionCodeCollectAmount"].ToString());
                }
                
                nGoodsCount0 = nGoodsCount - nGoodsCount1;
                txtGoodsCollectCount0.Text = nGoodsCount0.ToString();
                txtGoodsCollectCount1.Text = nGoodsCount1.ToString();
                txtBillCollectStatus.Text = "未采";
                txtBillCollectStatus.Text = nGoodsCount1 > 0 ? "部采" : txtBillCollectStatus.Text;
                txtBillCollectStatus.Text = (nGoodsCount1 > 0 && nGoodsCount1 == nGoodsCount) ? "全采" : txtBillCollectStatus.Text;
                txtBillCollectStatus.Text = (dGoodsCollectAmount == 0) ? "未采" : txtBillCollectStatus.Text;
                txtGoodsCount.Text = nGoodsCount.ToString();
            }
            catch (Exception ex)
            {
                CommFun._messageBoxShow(ex.Message);
                return;
            } 
        }

         /// <summary>
        /// 保存扫码信息
        /// </summary>
        /// <param name="strCode"></param>
        /// <param name="bIsNew"></param>
        private Boolean _saveCode()
        {
            Boolean bResult = false;
            try
            {
                // 保存数据
                string strSql = string.Format("exec P_DealPharmacyStockOut 'Collect_SaveSupervisionCode_Bat','{0}@{1}@{2}@{3}'", m_strBillCode, m_strSupervisionCode
                , AppInfo.m_UserInfo.m_strCode, AppInfo.m_UserInfo.m_strName);
                DataTable dt = AppInfo._openSql_DataTable(strSql);
                if (dt == null)
                {
                    CommFun._messageBoxShow("数据保存有误!");
                    return bResult;
                }
                else
                {
                    string strResultKind = dt.Rows[0]["Result"].ToString();
                    bResult = strResultKind.Equals("1");
                }
                // 保存失败
                if (!bResult)
                {
                    CommFun._messageBoxShow(dt.Rows[0]["Message"].ToString());
                    return bResult;
                }
                else
                {
                    // 数量加本次数量
                    m_bIsRefresh = true;
                    // 清除当前数据
                    SupervisionClear();
                    // 更新数据
                    _getBillList();
                    // 下一单
                    if (txtBillCollectStatus.Text.Equals("全采"))
                    {
                        // 清空数据
                        btnNext_Click(null, null);                        
                    }
                    bResult = true;
                }
            }
            catch {
                bResult = false;
            }
            return bResult;
        }

        /// <summary>
        /// 显示电监码信息(包含汇总信息)
        /// </summary>
        /// <param name="nKind"></param>
        private void _showSupervisionCode(int nKind = 0)
        {
            DataGridView dgv = new DataGridView();
            dgv = (nKind == 0) ? dataGridView_SupervisionCode : dataGridView_Total;
            if (dgv.DataSource != null)
            {
                ((DataTable)dgv.DataSource).Rows.Clear();
            }
            try
            {
                // 01 取数据
                string strSql = "";
                string strDataGridViewTitle = "";
                string strDataGridViewWidth = "";
                switch (nKind)
                {
                    case 0:
                        // 监管码信息
                        strSql = @"select 
Status = case when isnull(B.Code,'') = '' then '未对码' 
when isnull(C.Code,'') = '' then '非单据商品' 
when isnull(D.SupervisionCode,'') <> '' then '电监码已采' 
when isnull(E.ExpiredDate,Convert(date,getDate())) < Convert(date,getDate()) then '商品过期' 
else '正常' end
,A.SupervisionCode
,Amount = isnull(D1.PharmacyPackageRatio,1)
,B.Code
,Name = isnull(B.Name,E.Name)
,PackageSpec = isnull(B.PackageSpec,E.PackageSpec)
,Manufacturer = isnull(B.Manufacturer,E.Manufacturer)
,Unit = isnull(B.Unit,E.Unit)
from 
(                                      
  select SupervisionCode = Value,SupervisionCode_Short = left(Value,7) from dbo.F_Split('{0}',',') where Value <> '' group by Value                                      
)A
Left outer join TH_GoodsCheckSupervisionCode B On B.SupervisionCode = A.SupervisionCode_Short
Left outer join TH_PharmacyStockOutDetail C On C.StockOut_Code = '{1}' and B.Code = C.Code 
Left outer join TH_SupervisionCodeCollect D On D.SupervisionCode = A.SupervisionCode and D.BillKind = 'PharmacyStockOut' and isnull(D.IsReturn,0) = 0
Left outer join TH_PlatformSupervisionCode_Goods E On E.SupervisionCode = A.SupervisionCode_Short
Left outer join TH_Goods D1 On D1.Code = B.Code";
                        strDataGridViewTitle = "状态,电监码,药品数量,药品编码,药品名称,药品规格,生产厂家,单位";
                        strDataGridViewWidth = "80,150,80,80,150,150,200,0";
                        break;
                    case 1:
                        // 汇总信息
                        strSql = @"select Status = case when isnull(B.Code,'') = '' then '未对码' when isnull(C.Code,'') = '' then '非单据商品'
when B.SupervisionCode_Count * isnull(D.PharmacyPackageRatio,1) > (C.Amount - isnull(C.SupervisionCodeCollectAmount,0)) then '数量过多'
when B.SupervisionCode_Count * isnull(D.PharmacyPackageRatio,1) < (C.Amount - isnull(C.SupervisionCodeCollectAmount,0)) then '数量过少'
else '正常' end
,B.Code,B.SupervisionCode_Count,Amount = SupervisionCode_Count * isnull(D.PharmacyPackageRatio,1)
,D.Name,D.PackageSpec,D.Manufacturer
from
(
  select Code = isnull(B.Code,''), SupervisionCode_Count = sum(SupervisionCode_Count)
  from 
  (
    select SupervisionCode_Short = Left(SupervisionCode,7),SupervisionCode_Count = Count(*)
    from (
      select SupervisionCode = Value from dbo.F_Split('{0}',',') where Value <> '' group by Value
    ) A group by Left(SupervisionCode,7)
  )A
  Left outer join TH_GoodsCheckSupervisionCode B On A.SupervisionCode_Short = B.SupervisionCode
  group by isnull(B.Code,'')
)B
Left outer join TH_PharmacyStockOutDetail C On C.StockOut_Code = '{1}' and B.Code = C.Code
Left outer join TH_Goods D On D.Code = B.Code";
                        strDataGridViewTitle = "状态,药品编码,电监码数量,药品数量,药品名称,药品规格,生产厂家";
                        strDataGridViewWidth = "80,100,80,80,150,150,200";
                        break;
                    default:
                        break;
                }                
                strSql = string.Format(strSql, m_strSupervisionCode,m_strBillCode); 
                DataTable dt = null;
                dt = AppInfo._openSql_DataTable(strSql);

                dgv.DataSource = dt;
                // 02 设置列名称及宽度
                CommFun._setColumnNameDataGridView_String(dgv, strDataGridViewTitle);
                CommFun._setColumnWidthDataGridView_String(dgv, strDataGridViewWidth);
                dgv.AllowUserToAddRows = false;
            }
            catch (Exception ex)
            {
                CommFun._messageBoxShow(ex.Message);
                return;
            }

            switch (nKind)
            {
                case 0:
                    // 监管码信息
                    gbCodeInfo.Text = string.Format("电监码信息(数量：{0})", dgv.Rows.Count);
                    foreach (DataGridViewRow dr in dgv.Rows)
                    {
                        if (!dr.Cells["Status"].Value.ToString().Equals("正常"))
                        {
                            //dr.DefaultCellStyle.ForeColor = ColorTranslator.FromHtml("#E54646");
                            dr.DefaultCellStyle.ForeColor = ColorTranslator.FromHtml("#FF0000");
                        }
                    }
                    break;
                case 1:
                    // 汇总信息
                    int nAmount = 0;
                    foreach (DataGridViewRow dr in dgv.Rows)
                    {
                        nAmount += FunctionComm._strToInt(dr.Cells["SupervisionCode_Count"].Value.ToString());
                        if (!dr.Cells["Status"].Value.ToString().Equals("正常"))
                        {
                            dr.DefaultCellStyle.ForeColor = ColorTranslator.FromHtml("#FF0000");
                        }
                    }
                    lblCodeTotal.Text = string.Format("商品数据(商品种类数：{0},条码数量：{1})", dgv.Rows.Count, nAmount);
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 电监码对码
        /// </summary>
        /// <returns></returns>
        private void _checkHisCode(string strSupervisionCode)
        {
            if (CommFun._messageBoxShow("是否现在对该电监码进行对码？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
            {
                frmGoodsCodeCheck frm = new frmGoodsCodeCheck();
                frm.m_dictInfo.Add("Code", this.dataGridView_SupervisionCode.CurrentRow.Cells["SupervisionCode"].Value.ToString());
                frm.m_dictInfo.Add("Name", this.dataGridView_SupervisionCode.CurrentRow.Cells["Name"].Value.ToString());
                frm.m_dictInfo.Add("PackageSpec", this.dataGridView_SupervisionCode.CurrentRow.Cells["PackageSpec"].Value.ToString());
                frm.m_dictInfo.Add("Unit", this.dataGridView_SupervisionCode.CurrentRow.Cells["Unit"].Value.ToString());
                frm.m_dictInfo.Add("Manufacturer", this.dataGridView_SupervisionCode.CurrentRow.Cells["Manufacturer"].Value.ToString());
                if (frm.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                else
                {
                    // 刷新数据
                    _showSupervisionCode(0);
                    _showSupervisionCode(1);
                    return;
                }
            }
        }

        /// <summary>
        /// 电监码有效性校验
        /// </summary>
        /// <returns></returns>
        private Boolean _checkSupervisionCode()
        {
            Boolean bReturn = true;
            foreach (DataGridViewRow dr in dataGridView_SupervisionCode.Rows)
            {
                if (!dr.Cells["Status"].Value.ToString().Equals("正常"))
                {
                    CommFun._messageBoxShow("有商品核对不正常，请校对后再提交！");
                    bReturn = false;
                    return bReturn;
                }
            }
            foreach (DataGridViewRow dr in dataGridView_Total.Rows)
            {
                if (!dr.Cells["Status"].Value.ToString().Equals("正常"))
                {
                    CommFun._messageBoxShow("有商品数量核对不正常，请校对后再提交！");
                    bReturn = false;
                    return bReturn;
                }
            }
            if (bReturn && dataGridView_Total.Rows.Count > 0)
            {
                _saveCode();
            }
            return bReturn;
        }

        /// <summary>
        /// 电监码有效性校验及保存
        /// </summary>
        /// <returns></returns>
        private Boolean _checkSupervisionCode_New(Boolean bIsCollectHint = true, Boolean bIsCollectSave = true)
        {
            Boolean bReturn = true;
            string strMessageCode = ""; // 电监码错误
            string strTemp = "";
            foreach (DataGridViewRow dr in dataGridView_SupervisionCode.Rows)
            {
                if (!dr.Cells["Status"].Value.ToString().Equals("正常"))
                {
                    strTemp = dr.Cells["Status"].Value.ToString();
                    switch (strTemp)
                    {
                        case "未对码":
                            strTemp = string.Format("{0}:{1}", strTemp, dr.Cells["SupervisionCode"].Value.ToString());
                            break;
                        case "电监码已采":
                            strTemp = string.Format("{0}:{1}({2})", strTemp, dr.Cells["SupervisionCode"].Value.ToString(), dr.Cells["Name"].Value.ToString());
                            break;
                        case "非单据商品":
                            strTemp = string.Format("{0}:{1}", strTemp, dr.Cells["Name"].Value.ToString());
                            break;
                        case "商品过期":
                            strTemp = string.Format("{0}:{1}", strTemp, dr.Cells["Name"].Value.ToString());
                            break;
                        default:
                            break;
                    }
                    strMessageCode += (strMessageCode.Equals("") ? "" : ",") + strTemp;
                }
            }
            // 信息提示
            if (!strMessageCode.Equals("") && (bIsCollectHint || bIsCollectSave)) { 
                CommFun._messageBoxShow("电监码核对不正常，请校对！" + strMessageCode);
                bReturn = false;
                return bReturn;
            }
            strMessageCode = ""; 
            strTemp = "";
            foreach (DataGridViewRow dr in dataGridView_Total.Rows)
            {
                strTemp = dr.Cells["Status"].Value.ToString();
                if (!"正常,数量过少".Contains(strTemp))
                {
                    switch (strTemp)
                    {
                        case "未对码":
                            strTemp = string.Format("{0}:{1}", strTemp, dr.Cells["SupervisionCode"].Value.ToString());
                            break;
                        case "非单据商品":
                            strTemp = string.Format("{0}:{1}({2})", strTemp, dr.Cells["SupervisionCode"].Value.ToString(), dr.Cells["Name"].Value.ToString());
                            break;
                        case "数量过多":
                            strTemp = string.Format("{0}:{1}", strTemp, dr.Cells["Name"].Value.ToString());
                            break;
                        default:
                            break;
                    }
                    strMessageCode += (strMessageCode.Equals("") ? "" : ",") + strTemp;
                }
            }

            if (!strMessageCode.Equals(""))
            {
                CommFun._messageBoxShow("电监码核对不正常，请校对！" + strMessageCode);
                bReturn = false;
                return bReturn;
            }

            if (bIsCollectSave && bReturn && dataGridView_Total.Rows.Count > 0)
            {
                _saveCode();
            }
            return bReturn;
        }

        /// <summary>
        /// 清除电监码数据
        /// </summary>
        private void SupervisionClear()
        {
            m_strSupervisionCode = "";
            dataGridView_SupervisionCode.DataSource = null;
            dataGridView_Total.DataSource = null;
            //if (dataGridView_SupervisionCode.DataSource != null)
            //{
            //    ((DataTable)dataGridView_SupervisionCode.DataSource).Rows.Clear();
            //    ((DataTable)dataGridView_Total.DataSource).Rows.Clear();
            //}
            txtSupervisionCode.Text = "";
            txtSupervisionCode.Focus();               
        }
        #endregion

        #region  02 窗体相关事件方法
        private void frmConfig_Load(object sender, EventArgs e)
        {
            dataGridView_SupervisionCode.DefaultCellStyle.Padding = new System.Windows.Forms.Padding(0, 5, 0, 5);
            dataGridView_SupervisionCode.DefaultCellStyle.Font = new Font("宋体", 10); // 设置第一列的字体为Arial，大小为12
            dataGridView_SupervisionCode.RowTemplate.Height = 30;
            dataGridView_SupervisionCode.BackgroundColor = Color.White;
            dataGridView_Total.DefaultCellStyle.Padding = dataGridView_SupervisionCode.DefaultCellStyle.Padding;
            dataGridView_Total.DefaultCellStyle.Font = dataGridView_SupervisionCode.DefaultCellStyle.Font;
            dataGridView_Total.RowTemplate.Height = dataGridView_SupervisionCode.RowTemplate.Height;
            dataGridView_Total.BackgroundColor = dataGridView_SupervisionCode.BackgroundColor;
            this.pnlMain.BackColor = ColorTranslator.FromHtml("#d4e4f1");            
            this.DoubleBuffered = true;            
            pnlNext.Top = (this.Height - pnlNext.Height) / 2 - 20;
            pnlNext.Left = (this.Width - pnlNext.Width) / 2;   
            
            // 初始化10组明细
            _initCtrl(10);
            // 是否新单据
            if (!m_dictInfo.ContainsKey("BillCode"))
            {
                m_dictInfo.Add("BillCode", "");
            }
            // 动画
            AppInfo.AnimateWindow(this.Handle, 100, AppInfo.AW_CENTER | AppInfo.AW_ACTIVE | AppInfo.AW_VER_NEGATIVE);
            this.Refresh();
            timerShowData.Enabled = true;
            txtBillCode.Text = "";
            txtBillCollectStatus.Text = "";
            txtGoodsCollectCount0.Text = "";
            txtGoodsCollectCount1.Text = "";
            txtSupervisionCode.Text = "";
            txtCollectAmount1.Text = "";
        }

        private void frm_Resize(object sender, EventArgs e)
        {
            // 新单据位置调整居中
            this.DoubleBuffered = true;
            pnlNext.Top = (this.Height - pnlNext.Height) / 2 - 20;
            pnlNext.Left = (this.Width - pnlNext.Width) / 2;
        }

        private void timerShowData_Tick(object sender, EventArgs e)
        {
            timerShowData.Enabled = false;
            // 取单据号
            m_strBillCode = m_dictInfo["BillCode"].ToString();
            if (!m_strBillCode.Equals(""))
            {
                _showBillInfo(m_strBillCode);
                _getBillList();
                pnlNext.Visible = false;
                txtSupervisionCode.Text = "";
                txtSupervisionCode.Focus();
            }
            else {
                pnlNext.Visible = true;
            }            
        }
        #endregion

        #region  03 控件相关事件方法 

        private void pnlNext_VisibleChanged(object sender, EventArgs e)
        {
            if (pnlNext.Visible)
            {
                txtBillCode.Text = "";
                txtBillCode.Focus();
            }
            else
            {
                txtSupervisionCode.Text = "";
                txtSupervisionCode.Focus();
            }
            txtSupervisionCode.Enabled = !pnlNext.Visible;
            btnNext.Visible = !pnlNext.Visible;
            pnlMain.Enabled = !pnlNext.Visible;
        }

        private void txtBillCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnOK_Click(null, null);
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            // 取单据编号
            string strCode = txtBillCode.Text.Trim();
            if (strCode.Length < 2)
            {
                CommFun._messageBoxShow("编码位数太短,请确认！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                _showBillInfo(strCode);
                _getBillList();
                txtSupervisionCode.Focus();
                // 显示单据汇总信息
                //if (!pnlNext.Visible)
                //{
                //    timerShowData.Enabled = true;
                //}
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (!m_strBillCode.Equals("")) {
                pnlNext.Visible = false;
            }            
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (!pnlNext.Visible)
            {
                if (!txtGoodsCollectCount0.Text.Equals("0"))
                {
                    if (CommFun._messageBoxShow("当前单据未采码完成，是否确定要采集其他单据？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) != DialogResult.OK)
                    {
                        return;
                    }
                }
                SupervisionClear();
                pnlNext.Visible = true;
            }
        }

        private void btnReturn_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtSupervisionCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (txtSupervisionCode.Text.Trim().Length < 20) {
                    CommFun._messageBoxShow("电监编码长度不合法,应为20位！");
                    txtSupervisionCode.Text = "";
                    txtSupervisionCode.Focus();
                    return;
                }
                m_strSupervisionCode = (m_strSupervisionCode.Equals("")?"": m_strSupervisionCode + ",") + txtSupervisionCode.Text.Trim();
                _showSupervisionCode(0);
                _showSupervisionCode(1);
                if (AppConfig.m_bIsCollectHint || AppConfig.m_bIsCollectSave)
                {
                    _checkSupervisionCode_New(AppConfig.m_bIsCollectHint, AppConfig.m_bIsCollectSave);
                }                
                txtSupervisionCode.Text = "";
                txtSupervisionCode.Focus();
            }
        }

        private void btnScanSingle_Click(object sender, EventArgs e)
        {
            this.Hide();
            this.Close();
            frmCollectPharmacyStockOut frm = new frmCollectPharmacyStockOut();
            if (frm.m_dictInfo.ContainsKey("BillCode"))
            {
                frm.m_dictInfo["BillCode"] = m_strBillCode;
            }
            else
            {
                frm.m_dictInfo.Add("BillCode", m_strBillCode);
            }
            frm.ShowDialog();
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            // 校对数据
            if (!m_strSupervisionCode.Equals(""))
            {
                //_checkSupervisionCode();
                _checkSupervisionCode_New();
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            // 清空数据
            if (!m_strSupervisionCode.Equals(""))
            {
                DialogResult result = MessageBox.Show("是否确定要清空扫码信息?", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    SupervisionClear();
                }
            }
        }        

        private void btnReset_Click(object sender, EventArgs e)
        {
            if (!m_strBillCode.Equals(""))
            {
                DialogResult result = MessageBox.Show("是否确定要重置该单据扫码信息?", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    // 扫码重置
                    string strSql = string.Format("exec P_DealPharmacyStockOut 'Collect_Reset','{0}@{1}@{2}'", m_strBillCode, AppInfo.m_UserInfo.m_strCode, AppInfo.m_UserInfo.m_strName);

                    DataTable dt = AppInfo._openSql_DataTable(strSql);
                    // 重新显示数据
                    _showBillInfo(m_strBillCode);
                    _getBillList();
                    pnlNext.Visible = false;
                    txtSupervisionCode.Text = "";
                    txtSupervisionCode.Focus();
                }
            }
        }

        private void lblSupervisionCodeStatus1_DoubleClick(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("设置后系统会重置扫码数据，是否确定要设置电监码类型?", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                // 更改药品电监码类别       
                frmGoodsSetup frm = new frmGoodsSetup();
                string strName = ((LabelX)sender).Name;
                frm.m_strCode = m_dictCode[strName.Replace("txtSupervisionCodeStatus", "")];
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    // 重置扫码数据
                    btnReset_Click(null, null);
                };
            }
        }
        #endregion

        #region 04 dataGridViewX
        private void dataGridViewX1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            // 设置行序号
            DataGridViewRow CurrentRow = ((DataGridView)sender).Rows[e.RowIndex];
            CurrentRow.HeaderCell.Value = Convert.ToString(e.RowIndex + 1);

            if (((DataGridView)sender).CurrentRow.Index == e.RowIndex)
            {
                // 设置选定行的背景颜色  
                CurrentRow.DefaultCellStyle.BackColor = Color.LightBlue; // 将选定行的背景色设置为浅蓝色  
            }
            else
            {
                // 恢复其他行的默认背景颜色（可选）  
                CurrentRow.DefaultCellStyle.BackColor = Color.White;
            }
            
        }

        private void dataGridViewX1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            // 对码
            if (e.RowIndex >= 0)
            {
                string strSupplierCode = this.dataGridView_SupervisionCode.CurrentRow.Cells["SupervisionCode"].Value.ToString();
                _checkHisCode(strSupplierCode);
            }
        }
        #endregion

        private void btnDeleteSupervisionCode_Click(object sender, EventArgs e)
        {
            DataGridViewRow CurrentRow = dataGridView_SupervisionCode.CurrentRow;
            if (CurrentRow != null) {
                DialogResult result = MessageBox.Show("是否确定要删除该电监码信息?", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    string strTemp = CurrentRow.Cells["SupervisionCode"].Value.ToString();
                    m_strSupervisionCode = ("," + m_strSupervisionCode).Replace("," + strTemp, "");
                    _showSupervisionCode(0);
                    _showSupervisionCode(1);
                    txtSupervisionCode.Focus();
                }
            }
        }

        private void frmCollectPharmacyStockOut_Bat_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F5:
                    btnClear_Click(null, null);
                    break;
                case Keys.F9:
                    btnConfirm_Click(null, null);
                    break;
                case Keys.F12:
                    btnNext_Click(null, null);
                    break;                
                default:
                    break;
            }
            if (e.Alt && e.KeyCode == Keys.M)
            {
                this.WindowState = FormWindowState.Minimized;
                AppInfo.m_frmMain.WindowState = FormWindowState.Minimized; 
            }
        }

        private void txtGoodsCollectCount1_DoubleClick(object sender, EventArgs e)
        {
            if (FunctionComm._strToInt(((Label)sender).Text) >= 0)
            {
                frmQuery_BillSupervisionCodeCollect frm = new frmQuery_BillSupervisionCodeCollect();
                frm.m_strBillCode = m_strBillCode;
                frm.m_strBillKind = "PharmacyStockOut";
                frm.ShowDialog();
            }
        }

        private void txtCollectCount1_DoubleClick(object sender, EventArgs e)
        {
            if (FunctionComm._strToInt(((LabelX)sender).Text) > 0)
            {
                frmQuery_BillSupervisionCodeCollect frm = new frmQuery_BillSupervisionCodeCollect();
                frm.m_strBillCode = m_strBillCode;                
                frm.m_strBillKind = "PharmacyStockOut";
                string strName = ((LabelX)sender).Name;
                frm.m_strBillGoodsCode = m_dictCode[strName.Replace("txtCollectCount", "")];
                frm.ShowDialog();
            }
        }
    }
}
